import {
  List,
  SearchBar,
  Toast,
  Checkbox,
  InfiniteScroll,
  Picker,
} from "antd-mobile";
import {
  getProjectList,
  getQueryParamList,
  getSettleList,
} from "@/service/projectDetail";
import dayjs from "dayjs";
import { debounce } from "lodash-es";
import { useCallback, useEffect, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import Styles from "./index.module.less";
import store from "@/reducer/store";
import Cookies from "js-cookie";
import { update } from "@/reducer/ProjectInfo/action";
import {
  turnDept,
  realityName,
  loginUserType,
  loginUserTypes,
  identity,
} from "@/common/auth";
import { DownOutline } from "antd-mobile-icons";

const Index: React.FC<any> = () => {
  const navigate = useNavigate();
  const [search] = useSearchParams();
  const isSelectBox = search?.get("alone");
  const importProject = search?.get("importProject") || null;
  const isImportProject = Number(importProject) == 1;
  const defaultType = Number(importProject) == 1
    ? ((loginUserTypes(Cookies.get("user_deptName")) != 2 || Cookies.get('user_isAdmin') == '1') ? 2 : 3)
    : isSelectBox || 1;
  const current = search.get("label");
  const infoId = search.get("infoId");
  const selectType = search.get("selectType");
  const [value, setValue] = useState("");
  const [listInfo, setListInfo] = useState<any>({
    num: 1,
    list: [],
    pageSize: 10,
    hasMore: false,
  });

  const [sortList, setSortList] = useState<any[]>([
    {
      label: "意向投资额",
      color: "#B359F5",
      sort: 0,
    },
    {
      label: "对GDP拉动预估",
      color: "#0F9DE9",
      sort: 0,
    },
  ]);
  const [tabList, setTabList] = useState<any[]>([
    { name: "洽谈对接", isSelect: 1, type: 1 },
    { name: "引进落户", isSelect: 0, type: 2 },
  ]);

  const [negotiationInfo, setNegotiationInfo] = useState<any>({});

  const [isSelect, setIsSelect] = useState(defaultType);
  const [labelList, setLabelList] = useState<any>([]);
  const [currentLabel, setCurrentLabel] = useState<any>(current);
  const [visible, setVisible] = useState(false);

  // 点击搜索查询事件
  const handleSearch = debounce(async () => {
    if (!value.length) {
      Toast.show("请输入项目名称关键字");
      return;
    }
    setListInfo((state: any) => ({
      ...state,
      list: [],
      num: 1,
      hasMore: false,
    }));
    getList(value);
  }, 300);

  const startTime = search?.get("starTime") || null;
  const endTime = search?.get("endTime") || null;
  const tabType = tabList.find((item) => !!item.isSelect)?.type ?? 1; //洽谈对接等tab选中的值
  const investmentSort = sortList[0].sort;
  const gdpSort = sortList[1].sort;

  const getList = async (projectName: any, isLoadMore?: number, name?: any) => {
    const tType = tabList?.find((item) => !!item.isSelect)?.type ?? 1;
    const lApi = tType === 1 ? getProjectList : getSettleList;
    let dataType = loginUserType;

    let params: any = {
      dataType,
      isSelect: [1, 3].includes(Number(isSelect)) ? 1 : 0,
      deptName:
        dataType == 2 || (dataType == 3 && isSelect == 1) ? turnDept : null,
      startDate: startTime,
      endDate: endTime,
      ...(selectType ? { selectType: Number(selectType) } : {}),
      keyword: projectName ?? null,
      ...(dataType == 1 && isSelect == 1 ? { leaderName: realityName } : {}),
      pageNum: isLoadMore ? listInfo.num : 1,
      ...(infoId ? { infoId: infoId } : {}),
      pageSize: listInfo.pageSize,
      labelName: (name || currentLabel) ?? null,
    };
    if (!isImportProject)
      params = {
        ...params,
        gdpSort: gdpSort === 0 ? null : gdpSort,
        investSort: investmentSort === 0 ? null : investmentSort,
      };

    const res: any = await lApi(params);
    const { data, code } = res.data;
    if (code === 0) {
      const append = data?.list?.list || [];
      setNegotiationInfo({
        num: data?.num,
        planInvestVolume: data?.planInvestVolume,
      });
      setListInfo((state: any) => ({
        ...state,
        list: [...state.list, ...append],
        num: state.num + 1,
        hasMore: listInfo.num < data?.list?.pages,
      }));
    }
  };

  const getQueryParam = async () => {
    const res: any = await getQueryParamList({});
    const { code, data } = res?.data;
    if (code == 0) {
      let list: any = data?.label?.map((item: any) => {
        return {
          label: item,
          value: item,
        };
      });
      setCurrentLabel(current);
      setLabelList([list]);
    }
  };

  // 点击跳转详情
  const navigator = (item: any) => {
    store.dispatch(
      update({
        lastJointTime: item?.lastJointTime,
        leaderName: item?.leaderName,
        planInvestVolume: item?.planInvestVolume,
        companyName: item?.companyName,
        settledAppeal: item?.settledAppeal,
        team: item?.teams,
        turnDept: item?.turnDept,
        projectName: item?.projectName,
        labelNames: item?.labelNames,
      })
    );
    navigate(`/project-detail?id=${item?.id}&type=${item.status}`);
  };

  const changeSort = (idx: any, val: any) => {
    setListInfo((state: any) => ({
      ...state,
      list: [],
      num: 1,
      hasMore: false,
    }));
    setSortList((params: any) => {
      params = params.map((item: any, index: any) => {
        if (idx != index) {
          item.sort = 0;
        }
        return item;
      });
      if (val == params[idx].sort) {
        params[idx].sort = 0;
      } else {
        params[idx].sort = val;
      }
      return [...params];
    });
  };

  useEffect(() => {
    getQueryParam();
  }, []);
  useEffect(() => {
    window.scrollTo(0, 0);
    getList(value);
  }, [sortList, tabList, isSelect]);

  const renderTag = (item: any) => {
    const tagList = item?.split(",");
    let tagLists = [];
    if (tagList?.length > 2) {
      tagLists = [...tagList?.slice(0, 2), "..."];
    } else {
      tagLists = tagList;
    }
    return (
      <div className={Styles.tag_list}>
        {tagLists?.map((element: any, index: any) => {
          return (
            <div key={index} className={Styles.tag_font}>
              {element}
            </div>
          );
        })}
      </div>
    );
  };

  const clearOnCancelInfo = () => {
    setListInfo((state: any) => ({
      ...state,
      list: [],
      num: 1,
      hasMore: false,
    }));
    getList(null);
  };

  const jointStatusTitle: any = {
    1: "接触非实控人",
    2: "接触实控人",
    3: "线上对接",
    4: "线下拜访",
    5: "实地看房/考察",
    6: "组建项目专班",
    7: "形成落户方案",
    8: "政策匹配",
    9: "选定办公地址",
    10: "签署合作协议/合作备忘录",
    11: "新注册",
    12: "区外迁入",
    13: "虚拟地址入驻",
    14: "签订落户协议",
    15: "暂未入驻办公",
    16: "已入驻办公",
    17: "暂未投产运营",
    18: "已投产运营",
    19: "暂未入库纳统",
    20: "已入库纳统",
  };

  document.title = Number(importProject) == 1 ? "重大招商项目" : "招商项目库";
  console.log(Cookies.get('user_isAdmin') == '1');
  

  return (
    <div className={Styles.storage_container}>
      <div className={Styles.stick_content_top}>
        <div className={Styles.search_container}>
          <SearchBar
            placeholder="请输入企业投资方/项目名称关键词"
            showCancelButton={true}
            cancelText="查询"
            onClear={clearOnCancelInfo}
            clearOnCancel={false}
            onCancel={handleSearch}
            onChange={setValue}
          />
        </div>

        {!isImportProject && (
          <div className={`${Styles.tab_c} d_flex`}>
            {tabList.map((item: any, i: number) => (
              <div
                key={i}
                className={`${Styles.item} ${item.isSelect ? Styles.isActive : ""
                  }`}
                onClick={async () => {
                  if (tabType === item.type) return;
                  setListInfo((state: any) => ({
                    ...state,
                    list: [],
                    num: 1,
                    hasMore: false,
                  }));
                  const nArr = [...tabList].map((item, cI) => ({
                    ...item,
                    isSelect: i === cI ? 1 : 0,
                  }));
                  setTabList(() => nArr);
                  setSortList([
                    {
                      label: "意向投资额",
                      color: "#B359F5",
                      sort: 0,
                    },
                    {
                      label: "对GDP拉动预估",
                      color: "#0F9DE9",
                      sort: 0,
                    },
                  ]);
                }}
              >
                {item.name}
              </div>
            ))}
          </div>
        )}

        <div className="d_between_center mt_12 p_l_r_12">
          <div className="color_999 fontsize_14">
            洽谈对接数{negotiationInfo?.num}个,意向投资额
            {negotiationInfo?.planInvestVolume}亿元
          </div>
          {Number(isSelectBox) != 4 && (
            <div className={`d_between_center`}>
              <Checkbox
                style={{
                  "--icon-size": "18px",
                  "--font-size": "14px",
                  "--gap": "6px",
                }}
                disabled={
                  Number(isSelectBox) == 3 ||
                  !([
                    ...identity["districtLeaders"],
                    ...identity["superManagement"],
                  ].includes(Cookies.get("user_deptName") || "") || Cookies.get('user_isAdmin') == '1')
                }
                defaultChecked={[1, 3].includes(Number(isSelect))}
                onChange={(e) => {
                  if (isSelect != 3) {
                    setValue("");
                    setListInfo((state: any) => ({
                      ...state,
                      list: [],
                      num: 1,
                      hasMore: false,
                    }));

                    setIsSelect(isSelect == 1 ? 2 : 1);
                  }
                }}
              >
                <span className={"fontsize_14 color_333"}>仅看我的</span>
              </Checkbox>
            </div>
          )}
        </div>

        {!isImportProject && (
          <div className={Styles.sort_c}>
            {sortList.map((item: any, index: number) => (
              <div className="d_center_center mr_20" key={index}>
                <div
                  className={Styles.box}
                  style={{ backgroundColor: item.color }}
                ></div>
                <span>{item.label}</span>
                <span className={Styles.sortIcons}>
                  <div
                    className={`${Styles.sortUp} ${item.sort == 1 ? Styles.sortActive : ``
                      }`}
                    onClick={() => changeSort(index, 1)}
                  ></div>
                  <div
                    className={`${Styles.sortDown} ${item.sort == 2 ? Styles.sortActive : ``
                      }`}
                    onClick={() => changeSort(index, 2)}
                  ></div>
                </span>
              </div>
            ))}
          </div>
        )}
        {current && (
          <div
            className={Styles.select_tag_name}
            onClick={() => setVisible(true)}
          >
            <span className="mr_12">{currentLabel}</span>
            <DownOutline />
          </div>
        )}
        {labelList?.length > 0 && (
          <Picker
            columns={labelList || []}
            visible={visible}
            onClose={() => {
              setVisible(false);
            }}
            value={[currentLabel]}
            onConfirm={(e) => {
              setCurrentLabel(e?.[0]);
              setListInfo((state: any) => ({
                ...state,
                list: [],
                num: 1,
                hasMore: false,
              }));
              getList(null, 0, e?.[0]);
            }}
          />
        )}
      </div>
      <List className={Styles.content}>
        {listInfo.list?.map((item: any, i: any) => (
          <div
            key={i}
            className={Styles.content_item}
            onClick={() => navigator(item)}
          >
            <div className={Styles.title}>{item?.projectName}</div>
            {renderTag(item?.labelNames)}
            <div className={`${Styles.detail} mt_5 pt_12`}>
              企业（项目投资方）：
              <span style={{ color: "#333333" }}>
                {item?.companyName || "-"}
              </span>
            </div>
            <div className={`${Styles.detail} mt_5`}>
              对接领导：
              <span style={{ color: "#333333" }}>
                {item?.leaderName || "-"}
              </span>
            </div>
            <div className={`${Styles.detail} mt_5`}>
              招商小组：
              <span style={{ color: "#333333" }}>
                {item?.teams?.length > 0 ? (
                  <span>
                    {item?.teams?.map((item: any, currentIndex: any) => {
                      return (
                        <span key={currentIndex}>
                          {item?.teamMember?.map((element: any, index: any) => {
                            return (
                              <span key={index}>{`${element?.toString()}${index + 1 < item?.teamMember?.length ? "、" : ""
                                }`}</span>
                            );
                          })}
                          {currentIndex + 1 < item?.teams?.length ? "/" : ""}
                        </span>
                      );
                    })}
                  </span>
                ) : (
                  "-"
                )}
              </span>
            </div>
            {tabType === 1 && (
              <div className={`${Styles.detail} mt_5`}>
                最后一次对接时间：
                <span style={{ color: "#333333" }}>
                  {item?.lastJointTime
                    ? dayjs(item?.lastJointTime).format("YYYY年MM月DD日")
                    : "-"}
                </span>
              </div>
            )}

            {isImportProject && (
              <>
                <div className={`${Styles.detail} mt_5`}>
                  对GDP拉动：
                  <span style={{ color: "#333333" }}>
                    {item?.gdpRate || "-"}
                  </span>
                </div>
                <div className={`${Styles.detail} mt_5`}>
                  意向投资额：
                  <span style={{ color: "#333333" }}>
                    {item?.planInvestVolume
                      ? `${item?.planInvestVolume}亿元`
                      : "-"}
                  </span>
                </div>
              </>
            )}
            {tabType === 1 && !isImportProject && (
              <div className={`${Styles.detail} mt_5`}>
                对接状态：
                <span style={{ color: "#333333" }}>
                  {item?.jointStatus ? (
                    <span>
                      {item?.jointStatus
                        ?.split(",")
                        .map((item: any, index: number) => {
                          return (
                            <span>
                              {index != 0
                                ? `，${jointStatusTitle[item]}`
                                : jointStatusTitle[item]}
                            </span>
                          );
                        })}
                    </span>
                  ) : (
                    "-"
                  )}
                </span>
              </div>
            )}
            {tabType === 1 && (
              <div
                className={`${Styles.detail} mt_5`}
                style={{ display: "flex" }}
              >
                <p style={{ flex: 1 }}>落户诉求：</p>
                <p className={Styles.settle_title}>
                  {item?.settledAppeal || "-"}
                </p>
              </div>
            )}

            {!isImportProject && (
              <div className={`${Styles.num_box} mt_10`}>
                <div>
                  <p className={`${Styles.investment_num}`}>
                    {item?.planInvestVolume || "-"}
                  </p>
                  <p className={`${Styles.des}`}>意向投资额(亿元)</p>
                </div>
                <div>
                  <p className={`${Styles.gdp_num}`}>{item?.gdpRate || "-"}</p>
                  <p className={`${Styles.des}`}>对GDP拉动预估</p>
                </div>
              </div>
            )}
          </div>
        ))}
      </List>
      <InfiniteScroll
        loadMore={() => getList(value, 1)}
        hasMore={listInfo.hasMore}
        threshold={200}
      />
    </div>
  );
};
export default Index;
